package com.rong.mbt.personal.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.activity.base.PBaseActivity;
import com.rong.mbt.personal.utils.DlgUtil;
import com.rong.mbt.personal.utils.ImageUtil;

import java.io.File;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class Recharge2LoadImgActivity extends PBaseActivity {


    private EditText etNumber;
    private String mbtToken;
    private ProgressDialog imageDlg;

    static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    private static final int REQUEST_PERMISSION = 4;  //权限请求
    private static final int REQUEST_PICK_IMAGE = 1; //相册选取
    private Uri imageUri;//原图保存地址
    private String imagePath;
    private ImageView ivImage;

    @Override
    public int getLayoutId() {
        return R.layout.activity_recharge2_load_img;
    }

    @Override
    public void initView() {
        super.initView();
        mPermissionsChecker = new PermissionsChecker(this);
        mbtToken = getIntent().getStringExtra("mbtToken");

        find();
    }

    private void find() {
        findViewById(R.id.head_blue_iv_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.head_blue_tv_center);
        tvTitle.setText("申请充值");
        findViewById(R.id.head_blue_iv_right).setVisibility(View.GONE);


        etNumber = findViewById(R.id.act_arli_et);
        ivImage = findViewById(R.id.act_arli_iv);

        ivImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        startPermissionsActivity();
                    } else {
                        selectFromAlbum();
                    }
                } else {
                    selectFromAlbum();
                }
            }
        });


        findViewById(R.id.act_arli_bt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String monkey = etNumber.getText().toString();
                if (monkey.isEmpty()) {
                    return;
                }
                loadingImg(monkey);
            }
        });
    }

    private void loadingImg(final String monkey) {
//        File file = new File("/storage/emulated/0/DCIM/Camera/IMG_20180916_144856.jpg");
        File file = new File(imagePath);

        Luban.with(Recharge2LoadImgActivity.this).load(file)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        imageDlg = DlgUtil.showProgressDlg(Recharge2LoadImgActivity.this, "正在加载中...");
                    }

                    @Override
                    public void onSuccess(File file) {
                        OkGo.<String>post("http://service.jiangaifen.com:38082/user/addMon")
                                .tag(this)
                                .isMultipart(true)
                                .headers("mbtToken", mbtToken)
                                .params("price", monkey)
                                .params("file", file)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(Response<String> response) {
                                        Log.i("test", "addMon  " + response.body() + "  " + response.message());
                                        JSONObject jsonObject = JSON.parseObject(response.body());
                                        if (jsonObject.getIntValue("resultCode") == 0) {
                                            Toast.makeText(Recharge2LoadImgActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                            finish();
                                        } else {
                                            Toast.makeText(Recharge2LoadImgActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        Log.i("test", "addMon onError  " + response.body());
                                    }
                                });
                        imageDlg.cancel();
                    }

                    @Override
                    public void onError(Throwable e) {
                        imageDlg.cancel();
                    }
                }).launch();
    }


    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, REQUEST_PERMISSION,
                PERMISSIONS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_PERMISSION://权限请求
                if (resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
                    finish();
                } else {
                    selectFromAlbum();
                }
                break;

            case REQUEST_PICK_IMAGE://从相册选择
                if (data != null) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                    ImageUtil.loadImage(Recharge2LoadImgActivity.this, new File(imagePath), ivImage);
                }
                break;
        }
    }

    /**
     * 从相册选择
     */
    private void selectFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, REQUEST_PICK_IMAGE);
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        imagePath = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            imagePath = imageUri.getPath();
        }
    }


    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection老获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void handleImageBeforeKitKat(Intent intent) {
        imageUri = intent.getData();
        imagePath = getImagePath(imageUri, null);
    }
}

